package xyz.hubery.match;

import com.lmax.disruptor.EventHandler;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import xyz.hubery.disruptor.OrderEventHandler;
import xyz.hubery.model.OrderBooks;
import xyz.hubery.disruptor.OrderEvent;
import xyz.hubery.util.DepthCacheManager;

import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;

@Configuration
@EnableConfigurationProperties(value = MatchEngineProperties.class)
public class MatchEnginAutoConfiguration {

    @Autowired
    private DepthCacheManager depthCacheManager;

    private MatchEngineProperties matchEngineProperties;

    public MatchEnginAutoConfiguration(MatchEngineProperties matchEngineProperties) {
        this.matchEngineProperties = matchEngineProperties;
    }

    @Bean("eventHandlers")
    public EventHandler<OrderEvent>[] eventHandlers() {
        Map<String, MatchEngineProperties.CoinScale> symbols = matchEngineProperties.getSymbols();
        if(symbols == null || symbols.isEmpty()) {
            return new EventHandler[0];
        }
        EventHandler<OrderEvent>[] eventHandlers = new EventHandler[symbols.size()]; // 一个交易对对应一个事件处理器

        Set<String> keyedSet = symbols.keySet();
        int i = 0;
        for (String symbol : keyedSet) {
            MatchEngineProperties.CoinScale coinScale = symbols.get(symbol);
            OrderBooks orderBooks = null;
            if (coinScale != null) {
                orderBooks = new OrderBooks(symbol, coinScale.getCoinScale(), coinScale.getBaseCoinScale());
            } else {
                orderBooks = new OrderBooks(symbol);
            }
            orderBooks.initialize();
            eventHandlers[i++] = new OrderEventHandler(orderBooks);
            // 将事件处理器信息注册到Map集合中
            depthCacheManager.registerHandler((OrderEventHandler) eventHandlers[i-1]);
        }
        return eventHandlers;
    }
}
